package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.sun.org.apache.xml.internal.security.utils.Base64
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.GeneralSecurityException
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import java.text.SimpleDateFormat


/**
 *
 * @Title: apiJdRetryOrderBack*
 * @Description:提供给H5将京东养车名单推送到电销 *
 * @remak ：提供给H5将京东养车名单推送到电销*
 * @author: TH*
 * @date 2024-04-01 11:11:00
 *
 */
public  class apiJdRetryOrderBack implements  ServiceBackInvoke{

    private static final Log log = LogFactory.getLog(apiJdRetryOrderBack.class);
    private static String defaultCharset = "UTF-8";
    static String algorithm = "SHA256WITHRSA";
    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        String backXml=null;


        JSONObject backjson=new JSONObject();
        JSONObject headbodyjson=new JSONObject();
        long starttime = System.currentTimeMillis();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);

        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);
        }

        try {
            JSONObject datajson=JSONObject.fromObject(inData);

            String orderNo=datajson.getString("orderNo");
            String obj_guid=datajson.getString("obj_guid");

            Date date=new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dates=dateFormat.format(date);
            String clientName = KHDBConfig.getParam(eliteBean, "JD_SHH", "");//商户号
            String privateKey = KHDBConfig.getParam(eliteBean, "H5_KEY", "");//私钥

            //获取H5URL
            String sql = "select WEBSERVICEURL From sysc_interface where WEBTYPE='H5JDCS'";
            List<Map<String, Object>> createlist = jt.queryForList(sql);
            String geturl = createlist.get(0).get("WEBSERVICEURL")+clientName.toString()+"reTryOrderBack";


            log.debug("【京东养车】调用H5订单重试接口请求地址:"+geturl.toString());

            String msgId = KHUtil.getRandomString(36);
            String get36 = KHUtil.getRandomString(36);

            //请求报文
          String  xmljson = """<?xml version="1.0" encoding="UTF-8"?>
<request>
    <head>
        <msgId>$msgId</msgId>
        <session>$get36</session>
        <timeStamp>$dates</timeStamp>
        <clientName>$clientName</clientName>
        <userCode>$obj_guid</userCode>
    </head>
    <body>
        <order>
        <orderNo>$orderNo</orderNo>
        </order>
    </body>
</request>""";
            log.debug("调用H5订单重试接口报文:" + xmljson.toString());

            //对报文进行加签
            byte[] signBytes;
            String respEncode = Base64.encode(xmljson.getBytes(defaultCharset));

            log.debug("respEncode:" + respEncode)
            signBytes = sign(respEncode.replace("\n", "").getBytes(), Base64.decode(privateKey), algorithm);
            String respSign = Base64.encode(signBytes, Integer.MAX_VALUE);

            log.debug("respSign:" + respSign);

            //设置请求表头
            Map<String, String> TokenParams = new HashMap<String, String>();
            TokenParams.put("TP-SIGN", respSign);
            //调用请求H5
            String    postCallBackBody = Util.doHttpPostUseHead(geturl.toString(), xmljson.toString(), "UTF-8", 60000, 0, TokenParams, "");

            log.debug("【京东养车】调用H5订单重试接口返回报文:" + postCallBackBody);
            def xmlstr = Util.Transform(postCallBackBody);
            def LIST = new XmlParser().parseText(xmlstr);

            String status = LIST.head.status.text();//返回报文标识    S/成功 F/失败
            String errCode = LIST.head.errCode.text();//返回报文失败编码
            String errMsg = LIST.head.errMsg.text();//返回报文失败消息

            if (status.equals("S")) {

                backjson.put("code",1);
                backjson.put("msg","【京东养车】调用H5订单重试接口处理成功！");


            }else{
                backjson.put("code",-1);
                backjson.put("msg","【京东养车】调用H5订单重试接口处理失败："+errMsg);
            }



        } catch (Exception e) {
            log.error("调用H5订单重试接口异常：" + e.getMessage());
            backjson.put("code",-1);
            backjson.put("msg","【京东养车】调用H5订单重试接口异常："+e.getMessage());
        }




        return backjson.toString();
    }


    public static byte[] sign(final byte[] text, final byte[] privateKeyData,
                              final String algorithm) throws GeneralSecurityException {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyData);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        Signature signatureChecker = Signature.getInstance(algorithm);
        signatureChecker.initSign(privateKey);
        signatureChecker.update(text);
        return signatureChecker.sign();
    }
}
